package com.bolt.auth.security.common.feign;

import com.bolt.auth.security.common.constant.TraceConstant;
import com.bolt.auth.security.common.utils.TokenUtil;
import com.bolt.common.BoltConstants;
import com.bolt.common.collection.IteratorUtil;
import com.bolt.common.utils.StrUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;

import java.util.Collection;

/**
 * Created by Administrator on 2020/2/28.
 */
public class FeignInterceptorConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        RequestInterceptor requestInterceptor = new RequestInterceptor() {

            @Override
            public void apply(RequestTemplate template) {

                Collection <String> fromHeader = template.headers().get(BoltConstants.FROM);
                if (IteratorUtil.isNotEmpty(fromHeader) && fromHeader.contains(BoltConstants.FROM_IN)) {
                    return;
                }

                String traceId = StrUtil.isNotEmpty(MDC.get(TraceConstant.LOG_TRACE_ID)) ? MDC.get(TraceConstant.LOG_TRACE_ID) : MDC.get(TraceConstant.LOG_B3_TRACEID);
                if (StrUtil.isNotEmpty(traceId)) {
                    template.header(TraceConstant.HTTP_HEADER_TRACE_ID, traceId);
                }


                //传递token
                //使用feign client访问别的微服务时，将accessToken header
                //config.anyRequest().permitAll() 非强制校验token
                if (StrUtil.isNotBlank(TokenUtil.getToken())) {
                    template.header(BoltConstants.AUTH_HEADER, TokenUtil.getToken());
                }
            }
        };

        return requestInterceptor;
    }
}


